﻿namespace SCCM_Client_Injector_2014
{
    using Microsoft.ConfigurationManagement.ManagementProvider;
    using Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine;
    using System;
    using System.Windows.Forms;

    internal class LoadCollections
    {
        private WqlConnectionManager connection;

        public LoadCollections(WqlConnectionManager WMIconnection)
        {
            this.connection = WMIconnection;
        }

        public void ListCollections(CheckedListBox checkListBoxCollections)
        {
            string query = "SELECT * FROM SMS_Collection";
            checkListBoxCollections.Items.Clear();
            foreach (IResultObject collections in this.connection.QueryProcessor.ExecuteQuery(query))
            {
                if (!(collections["Name"].StringValue == "Root Collection"))
                {
                    checkListBoxCollections.Items.Add(collections["Name"].StringValue);
                }
                Application.DoEvents();
            }
        }

        public void ListCollectionsWithFilter(CheckedListBox checkListBoxCollections, string CollectionNames, string FilterType)
        {
            string query = "SELECT * FROM SMS_Collection";
            checkListBoxCollections.Items.Clear();
            foreach (IResultObject collections in this.connection.QueryProcessor.ExecuteQuery(query))
            {
                if (collections["Name"].StringValue != "Root Collection")
                {
                    if (FilterType == "Contains")
                    {
                        if (collections["Name"].StringValue.IndexOf(CollectionNames, StringComparison.OrdinalIgnoreCase) != -1)
                        {
                            checkListBoxCollections.Items.Add(collections["Name"].StringValue);
                        }
                        Application.DoEvents();
                    }
                    else if (FilterType == "IsExactly")
                    {
                        if (string.Compare(collections["Name"].StringValue, CollectionNames, true) == 0)
                        {
                            checkListBoxCollections.Items.Add(collections["Name"].StringValue);
                        }
                        Application.DoEvents();
                    }
                    else if ((FilterType == "StartsWith") && collections["Name"].StringValue.StartsWith(CollectionNames, StringComparison.CurrentCultureIgnoreCase))
                    {
                        checkListBoxCollections.Items.Add(collections["Name"].StringValue);
                    }
                    Application.DoEvents();
                }
            }
        }
    }
}

